import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/Refresher.dart';
import 'package:huajianshe_app/common/AppRouter.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/pages/search/SearchPage.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CircleSearchAppBar.dart';

import 'LessonItem.dart';
import 'model/LessonModel.dart';

class LessonPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _LessonPageState();
  }
}

class _LessonPageState extends BaseState<LessonPage> {

  LessonHomeData? data;
  List<Lesson>? lessons;
  int page = 1;

  @override
  void initState() {
    super.initState();
    refresher = Refresher<Lesson>(this);
    refresher?.enablePullUp = false;
    loadHeader(false);
  }

  loadHeader(bool doNotShowProgressBar) {
    sendReq(Api.lessonHome(), LessonHomeResp(), data: {}, doNotShowProgressBar: doNotShowProgressBar);
  }

  load() {
    var data = {
      'list_rows': 10,
      'page': page,
      'lesson_type': 2
    };
    sendReq(Api.lessonList(), LessonListResp(), data: data, doNotShowProgressBar: true);
  }

  @override
  void onRefresh() {
    refresher?.mode = Mode.refresh;
    page = 1;
    loadHeader(true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is LessonHomeResp) {
      this.data = t.data;
      setState(() => null);
      load();
    } else if (t is LessonListResp) {
      lessons = t.data?.data;
      refresher?.load(t.data?.data);
      setState(() => null);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CircleSearchAppBar(SearchType.lesson),
      body: refresher?.build(buildChild())
    );
  }

  Widget? buildChild() {
    print('buildChild');
    // Widget? child = buildEmptyPage();
    // if (child != null) {
    //   print('empty buildChild');
    //   return child;
    // }
    // print('${refresher?.data?.length}');
    return
      ListView.separated(
          itemBuilder: (_, index) {
            if (index == 0) {
              return buildHeader();
            }
            return Padding(padding: EdgeInsets.symmetric(horizontal: 13),
                child: LessonItem(refresher?.data?[index - 1]));
            },
          separatorBuilder: (_, index) => index == 0 ? H(0) : H(15),
          itemCount: ((refresher?.data?.length ?? 0) + (this.data == null ? 0 : 1))
      );
  }

  Widget buildHeader() {
    return Column(mainAxisSize: MainAxisSize.min, children: [
      H(15),
      buildBanner(),
      H(20),
      buildCategory(),
      H(27),
      buildHotAndNew(),
      H(8),
      buildMasterHeader(),
      H(8)
    ]);
  }

  Widget buildBanner() {
    double height = 142;
    if (data?.banners?.isNotEmpty == true) {
      return Container(
        height: height,
        child: new Swiper(
          onTap: (i) => detail(data?.banners?[i].targetId),
          itemBuilder: (BuildContext context,int index){
            return LoadImage(data!.banners![index].url);
          },
          itemCount: data!.banners!.length,
          pagination: new SwiperPagination(),//如果不填则不显示指示点
          autoplay: true,
        ),
      );
    } else {
      return LoadImage('bg_user_info', width: double.infinity, height: height);
    }
  }

  Widget buildCategory() {
    return Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
      if (data?.categories?.isNotEmpty == true)
        ...data!.categories!.map((e) {
          return SmartButton(width: 52, height: 60, text: e.name ?? '', textColor: C.gray333, fontSize: 12, backgroundColor: Colors.transparent,
            borderColor: Colors.transparent, drawableTop: LoadImage(e.url, width: 30, height: 30), drawablePadding: 9, onPressed: () { specialLessonList(e.id, e.name); });
      }).toList(),
      SmartButton(width: 52, height: 60, text: '数据库', textColor: C.gray333, fontSize: 12, backgroundColor: Colors.transparent,
          borderColor: Colors.transparent, drawableTop: LoadImage('ic_database', width: 30, height: 30), drawablePadding: 9),
      SmartButton(width: 52, height: 60, text: '我的课程', textColor: C.gray333, fontSize: 12, backgroundColor: Colors.transparent,
          borderColor: Colors.transparent, drawableTop: LoadImage('ic_my_lesson', width: 30, height: 30), drawablePadding: 9, onPressed: myLessons,),
    ]);
  }

  Widget buildHotAndNew() {
    return
      SingleChildScrollView(padding: EdgeInsets.only(bottom: 10), scrollDirection: Axis.horizontal,
          child: Row(children: [
            W(12),
            RoundedCornerWidget(width: 260, height: 300, borderWidth: 0, radius: 13, backgroundColor: Colors.white,
                boxShadowList: [
                  BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.09), offset:  Offset(0, 1), blurRadius: 4)
                ],
                child: Stack(children: [
                  LoadImage('bg_lesson_hot'),
                  Column(children: [
                    H(20),
                    Row(children: [
                      W(12),
                      LoadImage('ic_crown'),
                      W(12),
                      Text('热门课程', style: TS(18, C.gray333, fontWeight: FontWeight.bold)),
                      Spacer(),
                      SmartButton(width: 60, text: '全部', textColor: C.gray999, fontSize: 12, borderColor: Colors.transparent, onPressed: allHots,
                        drawableRight: LoadImage('ic_gray_right_arrow', width: 6, height: 11,), drawablePadding: 6, backgroundColor: Colors.transparent,)
                    ]),
                    H(19),
                    buildItem(data?.hots, 0),
                    H(12),
                    buildItem(data?.hots, 1),
                    H(12),
                    buildItem(data?.hots, 2),
                  ])
                ])
            ),
            W(12),
            RoundedCornerWidget(width: 260, height: 300, borderWidth: 0, radius: 13, backgroundColor: Colors.white,
                boxShadowList: [
                  BoxShadow(color: Color.fromRGBO(0, 0, 0, 0.09), offset:  Offset(0, 1), blurRadius: 4)
                ],
                child: Stack(children: [
                  LoadImage('bg_lesson_new'),
                  Column(children: [
                    H(20),
                    Row(children: [
                      W(12),
                      Text('最新上架', style: TS(18, C.gray333, fontWeight: FontWeight.bold)),
                      Spacer(),
                      SmartButton(width: 60, text: '全部', textColor: C.gray999, fontSize: 12, borderColor: Colors.transparent, onPressed: allNew,
                        drawableRight: LoadImage('ic_gray_right_arrow', width: 6, height: 11,), drawablePadding: 6, backgroundColor: Colors.transparent,)
                    ]),
                    H(19),
                    buildItem(data?.newSales, 0),
                    H(12),
                    buildItem(data?.newSales, 1),
                    H(12),
                    buildItem(data?.newSales, 2),

                  ])
                ])
            ),
          ])
      );
  }

  Widget buildItem(List<Lesson>? lessons, int index) {
    if ((lessons?.length ?? 0) > index) {
      return
        InkWell(onTap: () => detail(lessons?[index].id), child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
          W(13),
          Stack(children: [
            ClipRRect(borderRadius: BorderRadius.circular(3),
              child: LoadImage(lessons?[index].cover, width: 91, height: 63),
            ),
            Positioned(child: RoundedCornerWidget(child: Center(
                child: Text('TOP${index + 1}', style: TS(11, Colors.white))),
                width: 30, height: 14, borderWidth: 0, radius: 3, cornerPosition: 2,
                gradient: LinearGradient(
                    begin: Alignment.topCenter, end: Alignment.bottomCenter,
                    colors: [Color(0xffFE2E2E), Color(0xffF78C58)])),
              bottom: 0,
            )
          ]),
          W(11),
          Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(lessons?[index].name ?? '', style: TS(14, C.gray333),
                maxLines: 1,
                overflow: TextOverflow.ellipsis),
            H(6),
            Text(lessons?[index].desc ?? '', style: TS(12, C.gray999),
                maxLines: 1,
                overflow: TextOverflow.ellipsis),
            H(6),
            Text('讲师:${lessons?[index].teacher}', style: TS(12, C.gray999),
                maxLines: 1,
                overflow: TextOverflow.ellipsis),
          ])
        ]));
    }
    return H(0);
  }

  Widget buildMasterHeader() {
    return
      Row(children: [
        W(13),
        Text('大师课程', style: TS(18, C.gray333, fontWeight: FontWeight.bold)),
        Spacer(),
        SmartButton(width: 66, text: '查看更多', textColor: C.gray999, fontSize: 12, borderColor: Colors.transparent, onPressed: allMasters,
          drawableRight: LoadImage('ic_gray_right_arrow'), drawablePadding: 6, backgroundColor: Colors.transparent,),
        W(13)
      ]);
  }

  allHots() { // 全部热门
    AppNavigator.push(context, RouteName.LESSON_LIST, arguments: {'recommendStatus': 1, 'title': '热门课程'});
  }

  allNew() { // 全部最新
    AppNavigator.push(context, RouteName.LESSON_LIST, arguments: {'isNewSale': 1, 'title': '最新上架'});
  }

  allMasters() { //全部大师
    AppNavigator.push(context, RouteName.LESSON_LIST, arguments: {'type': 1, 'title': '大师课程'});
  }

  specialLessonList(int? id, String? name) { // 专栏
    AppNavigator.push(context, RouteName.SPECIAL_LESSON_LIST, arguments: {'id': id, 'title': name});
  }

  myLessons() {
    AppNavigator.push(context, RouteName.MY_LESSONS);
  }

  detail(int? id) {
    AppNavigator.push(context, RouteName.LESSON_DETAIL, arguments: {'id': id});
  }
}